package com.wondersgroup.fjzlpt.tbxt.service.impl.sxzztz;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.quick.framework.util.ExcelOrWordUtils;
import com.quick.framework.util.FormatDate;
import com.wondersgroup.fjzlpt.tbxt.dao.inter.tz.SxzztzDao;
import com.wondersgroup.fjzlpt.tbxt.service.inter.sxzztz.SxzztzService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.*;

/**
 * 家庭医生签约台账
 */
@Service
public class SxzztzServiceImpl implements SxzztzService{

    @Autowired
    private SxzztzDao sxzztzDao;


    /**
     * 批量保存
     * @param map
     * @return
     */
    public JSONObject save(Map map){
        JSONObject result = new JSONObject();
        try {
            String type = map.remove("type").toString();
            if("add".equals(type)){
                this.insertBatch(map);
                result.put("info","保存成功!");
            }else{
                this.update(map);
                result.put("info","修改成功!");
            }
            result.put("state","true");
        }catch (Exception e){
            result.put("info","保存失败，请稍后再试!");
            throw new RuntimeException("保存失败，请稍后再试!");
        }
        return result;
    }

    /**
     * 批量保存
     * @param map
     */
    public void insertBatch(Map<String,Object> map){
        map.put("ADD_USERID",map.remove("USERID"));
        map.put("ADD_USERNAME",map.remove("USERNAME"));
        map.put("XZSJ",new Date()); //新增时间

        List<Map> listMaps = new ArrayList<Map>();

        String rows = map.remove("rows").toString();
        if(!StringUtils.isEmpty(rows)){
            JSONArray rowsArr = JSONArray.parseArray(rows);
            for(Object item : rowsArr){
                JSONObject itemObj = (JSONObject)item;
                itemObj.put("ID", UUID.randomUUID().toString());
                itemObj.putAll(map); //map中还包含：PTJGID、JGMC,XZSJ等其他字段。

                String FQZZSJ = itemObj.getString("FQZZSJ");
                if(FQZZSJ != null) itemObj.put("FQZZSJ", FormatDate.getDateY_M_D(FQZZSJ));
                String ZZYYSJ = itemObj.getString("ZZYYSJ");
                if(ZZYYSJ != null) itemObj.put("ZZYYSJ", FormatDate.getDateY_M_D(ZZYYSJ));
                itemObj.put("LYSJ", FormatDate.getDateY_M_D(itemObj.getString("LYSJ")));
                listMaps.add(itemObj);
            }
        }
        sxzztzDao.insertBatch(listMaps);
    }

    /**
     * 修改
     * @param map
     */
    public void update(Map map){
        map.remove("PTJGID");
        map.remove("JGMC");
        map.remove("JGLB");
        map.remove("XZQHDM");

        map.put("LYSJ", FormatDate.getDateY_M_D(map.get("LYSJ").toString()));
        map.put("UPDATE_USERID",map.remove("USERID"));
        map.put("UPDATE_USERNAME",map.remove("USERNAME"));
        map.put("GXSJ",new Date()); //更新时间
        Object FQZZSJ = map.get("FQZZSJ");
        if(FQZZSJ != null) map.put("FQZZSJ", FormatDate.getDateY_M_D(FQZZSJ.toString()));
        Object ZZYYSJ = map.get("ZZYYSJ");
        if(ZZYYSJ != null) map.put("ZZYYSJ", FormatDate.getDateY_M_D(ZZYYSJ.toString()));
        sxzztzDao.updateForPrimaryKey(map);
    }

    /**
     * 分页查询
     * @param map
     * @return
     */
    public JSONObject queryPage(Map map){
        return sxzztzDao.queryPage(map);
    }

    /**
     * 根据主键ID删除数据（不可恢复）
     * @param map
     * @return
     */
    public JSONObject delete(Map map){
        JSONObject result = new JSONObject();
        try {
            sxzztzDao.deleteForPrimaryKey(map);
            result.put("info","删除成功!");
            result.put("state","true");
        }catch (Exception e){
            result.put("info","删除数据失败，请稍后再试!");
            throw new RuntimeException("删除数据失败，请稍后再试!");
        }
        return result;
    }

    /**
     * 下载Excel模板
     * @param response
     */
    public void downExcelModel(HttpServletRequest request, HttpServletResponse response){
        JSONArray downData = new JSONArray();

        //表头
        StringBuffer titleStr = new StringBuffer();
        //type=zcModel || type=zrModel
        String type = request.getParameter("type");
        if("zcModel".equals(type)){
            type = "双向转诊转出-模板";
            titleStr.append("{'a':'申请转诊时间','b':'患者姓名','c':'证件号码','d':'转入医院','e':'转入科室',")
                    .append("'f':'转诊类型','g':'紧急程度','h':'是否履约','i':'履约时间','j':'是否签约'}");

        }else{
            type = "双向转诊转入-模板";
            titleStr.append("{'a':'转诊预约时间','b':'患者姓名','c':'证件号码','d':'转出医院','e':'转出科室',")
                    .append("'f':'转诊类型','g':'紧急程度','h':'是否履约','i':'履约时间','j':'是否签约'}");
        }
        JSONObject title = JSONObject.parseObject(titleStr.toString());
        downData.add(0, title);

        //排列循序
        List<String> titelField = new ArrayList<>();
        titelField.add("a");
        titelField.add("b");
        titelField.add("c");
        titelField.add("d");
        titelField.add("e");
        titelField.add("f");
        titelField.add("g");
        titelField.add("h");
        titelField.add("i");
        titelField.add("j");
        ExcelOrWordUtils.downLoadExcelFile(downData, titelField ,type,request, response);
    }

    /**
     * 解析上传的Excel数据
     * @param request
     * @return
     */
    public String parseExcalData(MultipartFile file, HttpServletRequest request){
        // 解析类型： importType=zcExcel  || importType=zrExcel
        String importType = request.getParameter("importType");
        String[] title = null;
        String[] titleField = null;
        if("zcExcel".equals(importType)){
            title = new String[] { "申请转诊时间","患者姓名", "证件号码", "转入医院", "转入科室",
                    "转诊类型","紧急程度", "是否履约", "履约时间", "是否签约"};
            titleField = new String[]{ "FQZZSJ","XM", "SFZH", "ZRYY", "ZRKS", "ZZLX","JJCD","SFLY","LYSJ","SFQY"};
        }else{
            title = new String[] { "转诊预约时间","患者姓名", "证件号码", "转出医院", "转出科室",
                    "转诊类型","紧急程度", "是否履约", "履约时间", "是否签约"};
            titleField = new String[]{ "ZZYYSJ","XM", "SFZH", "ZCYY", "ZCKS", "ZZLX","JJCD","SFLY","LYSJ","SFQY"};
        }

        JSONObject result = new JSONObject();
        try {
            result = ExcelOrWordUtils.parseExcalData(file.getInputStream(), title, titleField);
            if(result.getBoolean("state") && result.getJSONArray("data").size()>100){
                result.remove("data");
                result.remove("state");
                result.put("info","导入文件数据量请控制在100条以内!");
            }
        }catch (Exception e){
            throw new RuntimeException("解析Excel失败");
        }
        return result.toString();
    }

    /**
     * 查询双向转诊页签数据总量
     * @param map
     * @return
     */
    public JSONObject queryCount(Map map){
        JSONObject result = new JSONObject();
        try {
            result = sxzztzDao.queryCount(map);
            result.put("info","页签数据总量查询成功!");
            result.put("state","true");
        }catch (Exception e){
            result.put("info","页签数据总量查询失败!");
            throw new RuntimeException("页签数据总量查询失败!");
        }
        return result;
    }
}
